$( function() {
  var developerMode = false;

  // check if the browser supports basic Base64 encoding
  if ( !window.btoa )
    window.btoa = base64.encode;
  
  if( !window.atob )
    window.atob = base64.decode;

  // populate the settings URL from local storage
  var settingsURL = localStorage.dsViewExamples;
  if ( settingsURL === undefined || settingsURL === null ) {
    settingsURL = '';
  }
  $( "#txtSettingsURL" ).val( settingsURL );
  
  // event handlers for the tabs
  $( '#bt_config' ).click( function() {
    hideEverything();
    $( '#editor_config' ).toggle();
    var editor = ace.edit("editor_config");
    editor.resize();
    $( '#bt_config' ).css( "font-weight", "bold" );
  } );
  $( '#bt_html' ).click( function() {
    hideEverything();
    $( '#editor_html' ).toggle();
    var editor = ace.edit("editor_html");
    editor.resize();
    $( '#bt_html' ).css( "font-weight", "bold" );
  } );
  $( '#bt_javascript' ).click( function() {
    hideEverything();
    $( '#editor_javascript' ).toggle();
    var editor = ace.edit("editor_javascript");
    editor.resize();
    $( '#bt_javascript' ).css( "font-weight", "bold" );
  } );
  $( '#bt_css' ).click( function() {
    hideEverything();
    $( '#editor_css' ).toggle();
    var editor = ace.edit("editor_css");
    editor.resize();
    $( '#bt_css' ).css( "font-weight", "bold" );
  } );

  /**
   * EVENT LISTENER FOR THE RELOAD BUTTON
   */
  
  $("#btnReload").on("click", function(){
    if(confirm('You are about to reload the additional property window. Note that you need to re-select your design studio component afterwards.\n\nAre you sure you want to continue?.')){
      location.reload();
    };
  });
  
  /**
   * EVENT LISTENER FOR THE SAVE BUTTON IN THE SETTINGS WINDOW
   */
  $( '#btnSettingsSave' ).click( function() {
    
    // check if the URL has changed
    if( $("#txtSettingsURL").val() === localStorage.dsViewExamples){
      $( "#div_info2" ).dialog( "close" );
      return;
    }
    
    // reset the tree structure
    localStorage.dsViewExamples = $( "#txtSettingsURL" ).val();
    $( "#div_info2" ).dialog( "close" );
    alert('Please reselect your design studio component.');
    location.reload();
  } );

  $("#btnURL").on("click", function(){
      $( "#div_info2" ).dialog( {
        modal : true,
        width : 600,
        height : 150
      } );
  
      $( "#div_info2" ).dialog( "open" );
  });
  
  $("#btnLock").on("click", function(){
    // check if a developerkey is stored locally
    try{
      var developerkeyBase64 = localStorage.designstudioDeveloperkey;
      if(developerkeyBase64 === undefined || developerkeyBase64 === null || developerkeyBase64 === ""){
        developerkeyBase64 = prompt("Enter your developer key:", "Your developer key....");
      }
      if(developerkeyBase64 === undefined || developerkeyBase64 === null || developerkeyBase64 === ""){
        return;
      }
      
      var developerKey = JSON.parse( window.atob(developerkeyBase64) );
      if(!developerKey.developer){
        return;
      }
      // eyJkZXZlbG9wZXIiOnRydWV9
      // {"developer":true}
      localStorage.designstudioDeveloperkey = developerkeyBase64;
    }catch(error){
      alert(error.message);
      return;
    }
    
    var developerMode = ($("#btnLock").attr("data") === "developer");
   
    // toggle the divs
    if(developerMode){
      // switch to support mode
      $("#btnLock").attr("src", "");
      $("#btnLock").attr("data", "support");
      $("#supportWindow").show();
      $("#developerWindow").hide();
    }else{
      // switch to developer mode
      $("#btnLock").attr("src", "");
      $("#btnLock").attr("data", "developer");
      $("#supportWindow").hide();
      $("#developerWindow").show();
      $("#bt_config").trigger("click");
    }
  });
  
  $("#btnDocumentation").on("click", function(){
	  
	  // get the documentation from the configuration
	  try{
		  var editor = ace.edit("editor_config");	  
		  var configObject = JSON.parse( editor.getSession().getValue() ); 	  
		  $( "#div_documentation" ).html( window.atob( configObject.documentation ) );
		  $( "#div_documentation" ).dialog( {
		        modal : true,
		        width : $(window).width() * 0.95,
		        height : $(window).height() * 0.95
		      } );
		  
		   $( "#div_documentation" ).dialog( "open" );
	  }catch(err){
		  alert(err.message);
	  }
  });
  
  
  // set the heights of the editors
  var editorHeight = $( document ).height() - 70;
  $( "#editor_config" ).css( "height", editorHeight );
  $( "#editor_html" ).css( "height", editorHeight );
  $( "#editor_javascript" ).css( "height", editorHeight );
  $( "#editor_css" ).css( "height", editorHeight );


  // load the examples
  reloadExamples();
} );





// reload the examples
function reloadExamples() {

  // reset the predefined components
  $("#componentselector").html("");
  
  // remove the predefinedComponent functions
  getPredefinedComponentTree = undefined;
  getPredefinedComponentById = undefined;
  
  // reset config / html / javascript / css
  editor = ace.edit("editor_config"),
  editor.getSession().setValue( '' );
  editor = ace.edit("editor_html"),
  editor.getSession().setValue( '' );
  editor = ace.edit("editor_javascript"),
  editor.getSession().setValue( '' );
  editor = ace.edit("editor_css"),
  editor.getSession().setValue('');
  
  // get URL to load the settings from
  var settingsURL = $( "#txtSettingsURL" ).val();
  if ( settingsURL === "" ) {
    $("body").trigger("reloadExamples");
    return;
  }

  // load the URL
  head.load( settingsURL, function() {
    activatePredefinedComponents();    
  });
}


function hideEverything() {
  $( '#editor_config' ).hide();
  $( '#editor_html' ).hide();
  $( '#editor_javascript' ).hide();
  $( '#editor_css' ).hide();
  $( '#bt_config' ).css( "font-weight", "normal" );
  $( '#bt_html' ).css( "font-weight", "normal" );
  $( '#bt_javascript' ).css( "font-weight", "normal" );
  $( '#bt_css' ).css( "font-weight", "normal" );
}